package com.decoration.basic.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.decoration.basic.entity.*;
import com.decoration.basic.findCondition.DecDailyListCondition;
import com.decoration.basic.mapper.DecCtctionPhaseMapper;
import com.decoration.basic.mapper.DecPictureMapper;
import com.decoration.basic.po.DecCtctionInfVo;
import com.decoration.basic.service.DecPhaseService;
import com.decoration.basic.util.DateFormatUtils;
import com.decoration.basic.util.SnowFlake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.media.jfxmedia.logging.Logger;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import com.decoration.basic.mapper.DecDailyMapper;
import com.decoration.basic.findCondition.DecDailyFindCondition;
import com.decoration.basic.service.DecDailyService;

@Service
public class DecDailyServiceImpl implements DecDailyService {

	@Resource
	private DecDailyMapper dailymapper;
	@Resource
	private DecPictureMapper decPictureMapper;
	@Resource
	private DecCtctionPhaseMapper phaseMapper;

	@Override
	public List<DecorationDailyInf> findAll(DecDailyFindCondition findCondition) {

		List<DecorationDailyInf> dailyList = dailymapper.findAll(findCondition);

		// 获取相关图片信息

		return dailyList;
	}

	@Override
	public List<DecDailyOutMsg> getDailyList(DecDailyFindCondition findCondition) {
		List<DecDailyOutMsg> list = null;
		try {
			list = dailymapper.getDailyList(findCondition);
			//日报图片返回
			if (list != null && list.size() >1) {
				for (DecDailyOutMsg out : list) {
					List<String> piclist = new ArrayList<>();
					List<DecorationPicture> result = decPictureMapper.findByRetId(null,null ,null ,out.getDailyId() ,null );
					if (result != null && result.size() > 0){
						for (DecorationPicture pic : result){
							piclist.add(pic.getPicAddress());
						}
					}
					out.setPiclist(piclist);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 后端获取日报列表
	 * @param findCondition
	 * @return
	 */
	@Override
	public List<DecDailyOutMsg> searchDailyList(DecDailyListCondition findCondition) {
		if (StringUtils.isBlank(findCondition.getStartDate())){
			findCondition.setStartDate("1970-07-01");
		}
		if (StringUtils.isBlank(findCondition.getEndDate())){
			findCondition.setEndDate("2999-01-01");
		}

		//DateFormatUtils.convStrToStr(findCondition.getStartDate(),"yyyy-MM-dd" ,"yyyyMMdd" );
		PageHelper.startPage(findCondition.getPage(), findCondition.getDataCount());
		List<DecDailyOutMsg> dailyList = dailymapper.searchDailyList(findCondition);

		return dailyList;
	}

	@Override
	public Boolean delete(String id) throws DataAccessException {

		// 删除相关图片信息
		int num = dailymapper.delete(id);
		return num == 1 ? Boolean.TRUE : Boolean.FALSE;
	}

	@Override
	public int update(DecorationDailyInf category) throws DataAccessException {
		DecorationDailyInf oldDaily = dailymapper.findById(category.getDailyId());
		if (oldDaily == null){
			return 3;
		}
		//校验日期
		if (! oldDaily.getCurrentDate().equals(DateFormatUtils.format(new Date(),"yyyy-MM-dd" ))){
			DecorationDailyInf inpo = new DecorationDailyInf();
			inpo.setDailyId(category.getDailyId());
			inpo.setDailyFlag(1);
			inpo.setUpdateTime(new Date());
			dailymapper.update(inpo);
			return 2;
		}
		//校验用户id
		if(! oldDaily.getUserId().equals(category.getUserId())){
			return 0;
		}
		//校验信息
		DecorationDailyInf updateDaily = new DecorationDailyInf();
		updateDaily.setDailyDesc(category.getDailyDesc());
		updateDaily.setDailyId(category.getDailyId());

		// 更新
		int num = dailymapper.update(updateDaily);

		//更新日报图片地址内容
		decPictureMapper.deleteDailyPic(oldDaily.getDailyId());
		for (String address: category.getPicturelist()){
			DecorationPicture picture = new DecorationPicture();
			picture.setUserId(category.getUpdateId());
			picture.setPicInfId(String.valueOf(SnowFlake.getInstance().nextId()));
			picture.setPicAddress(address);
			picture.setDailyId(oldDaily.getDailyId());
			picture.setCtcId(oldDaily.getCtcId());
			picture.setFirFlag(0);

			decPictureMapper.add(picture);
		}

		return num == 1 ? 1 : 0;

	}

	@Override
	public JsonResult add(DecorationDailyInf category) throws DataAccessException {
		JsonResult result = new JsonResult();
		//查询日报的阶段
		PhaseUsers inpo = new PhaseUsers();
		inpo.setCtcId(category.getCtcId());
		inpo.setPerId(category.getUserId());

		DecPhaseInf outpo = phaseMapper.searchPhaseByPerAndCtcid(inpo);
		if (outpo == null){
			result.setCode(JsonResult.FAILED_CODE);
			result.setMsg("您名下该项目无正在施工的阶段,无法新增日报!");
			result.setData(new ArrayList<>());
			return result;
		}
		category.setPhaseId(outpo.getPhaseId());
		category.setFlowId(outpo.getFlowId());
		category.setPhaseName(outpo.getPhaseName());

		//插入日报图片内容
		//1.删除原来日报图片
		decPictureMapper.deleteDailyPic(category.getDailyId());
		category.setPictureFlag(1);
		if (category.getPicturelist() != null && category.getPicturelist().size()>0 ) {
			category.setPictureFlag(0);
			//2.新增日报图片
			for (String address : category.getPicturelist()) {
				DecorationPicture picture = new DecorationPicture();
				picture.setUserId(category.getUserId());
				picture.setPicInfId(String.valueOf(SnowFlake.getInstance().nextId()));
				picture.setPicAddress(address);
				picture.setDailyId(category.getDailyId());
				picture.setCtcId(category.getCtcId());
				picture.setFirFlag(0);

				decPictureMapper.add(picture);
			}
		}
		//新增日报信息
		int num = dailymapper.add(category);

		result.setCode(JsonResult.SUCCESS_CODE);
		result.setMsg("新增日报成功!");
		result.setCount(num);
		return result;
	}

	@Override
	public DecorationDailyInf findById(String dailyId,String userId) {

		DecorationDailyInf result = dailymapper.findById(dailyId);
		updateDailyFlag(result,userId);

		// 获取相关图片信息
		List<DecorationPicture> piclist = decPictureMapper.findByRetId(null, null, null, dailyId, null);
		result.setPicturelist(picturesToList(piclist));

		return result;
	}

	@Override
	public DecorationDailyInf searchByCurDate(DecorationDailyInf findCondition) {
		List<DecorationDailyInf> list = dailymapper.searchByCurDate(findCondition);
		DecorationDailyInf result = new DecorationDailyInf();
		if (list != null && list.size() > 0){
			result = list.get(0);
		}else {
			return null;
		}
		updateDailyFlag(result,findCondition.getUserId());
		// 获取相关图片信息
		List<DecorationPicture> piclist = decPictureMapper.findByRetId(null, null, null, result.getDailyId(), null);
		result.setPicturelist(picturesToList(piclist));

		return result;
	}

	@Override
	public int getDailyListSize(DecDailyFindCondition findCondition) {
		return dailymapper.getDailyListSize(findCondition);
	}

	private List<String> picturesToList(List<DecorationPicture> piclist){
		List<String> strs = new ArrayList<>();
		for (DecorationPicture pic : piclist){
			strs.add(pic.getPicAddress());
		}
		return strs;
	}

	private void updateDailyFlag(DecorationDailyInf result,String userId){
		String today = DateFormatUtils.getNowDay("yyyy-MM-dd");
		if (result != null && !today.equals(result.getCurrentDate())) {
			result.setDailyFlag(1);
			System.out.println("更新日报可编辑状态");
			DecorationDailyInf updatePo = new DecorationDailyInf();
			updatePo.setDailyFlag(1);
			updatePo.setDailyId(result.getDailyId());
			dailymapper.update(updatePo);
		}else{
			if (result != null && !result.getUserId().equals(userId) && result.getDailyFlag() == 0 ){
				result.setDailyFlag(1);
			}else {
				System.out.println("不更新日报可编辑状态");
			}
		}


	}
}
